<template>
	<view class="wrap">
		<view class="content">
			<u-form :model="form" ref="uForm">
				<view class="title">用户登录</view>
				<u-form-item prop="username">
					<u-input v-model="form.username" type="text" placeholder="请输入用户名" />
				</u-form-item>
				<u-form-item prop="password">
					<u-input v-model="form.password" type="password" placeholder="请输入密码" />
				</u-form-item>
				<button @click="login" class="login-btn">登录</button>
				<view class="register-text" @click="toRegister">还没有账号，立即注册</view>
			</u-form>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					username: '',
					password: ''
				}
			};
		},
		methods: {
			async login() {
				try {
					if (!this.form.username.trim()) {
						throw new Error('请输入用户名');
					}
					if (!this.form.password.trim()) {
						throw new Error('请输入密码');
					}

					const res = await uniCloud.callFunction({
						name: 'uni-id-cf',
						data: {
							action: 'login',
							params: this.form,
						}
					});

					if (res.result.code === 0) {
						// 登录成功，进行页面跳转或其他操作
						this.$u.toast('登录成功');
						this.$u.route('/pages/index/index');
					} else {
						throw new Error(res.result.msg);
					}
				} catch (error) {
					// 处理异常，显示错误消息
					this.$u.toast(error.message);
				}
			},
			toRegister() {
				this.$u.route('/pages/register/register');
			}
		}
	};
</script>

<style scoped>
	.wrap {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}

	.content {
		width: 300px;
		padding: 20px;
		border: 1px solid #ccc;
		border-radius: 5px;
	}

	.title {
		font-size: 20px;
		font-weight: bold;
		margin-bottom: 20px;
	}

	.login-btn {
		width: 100%;
		padding: 10px;
		background-color: #007bff;
		color: #fff;
		border: none;
		border-radius: 5px;
		cursor: pointer;
	}

	.login-btn:hover {
		background-color: #0056b3;
	}

	.register-text {
		margin-top: 10px;
		text-align: center;
		color: #007bff;
		cursor: pointer;
	}

	.register-text:hover {
		text-decoration: underline;
	}
</style>